package internet.service;

import com.example.internet.Request;
import com.example.internet.Response;
import internet.utils.BytesUtils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Random;
import java.util.UUID;

public class ContactsService {
    // 绑定端口
    private static final int PORT = 8888;

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(PORT);
        while (true) {
            System.out.println("等待接收客户端UDP数据报...");
            byte[] requestData = new byte[1024];
            DatagramPacket requestPacket = new DatagramPacket(requestData, requestData.length);
            socket.receive(requestPacket);
            int len = BytesUtils.getValidLength(requestData);
            byte[] requestBytes = BytesUtils.subByte(requestData, 0, len);
            Request request = Request.parseFrom(requestBytes);
            System.out.println("接收到客户端请求" + request.toString());
            Response response = Response.newBuilder()
                    .setUid(UUID.randomUUID().toString())
                    .build();
            byte[] responseData = response.toByteArray();
            DatagramPacket responsePacket = new DatagramPacket(responseData, responseData.length, requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.println("发送响应成功");
        }
    }
}
